package com.wang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {
    //直接返回jsp页面方式
    @RequestMapping("/s1")
    public String show() {

        return "hello1";
    }

    //模型和视图返回
    @RequestMapping("/s2")
    public ModelAndView show2() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");
        modelAndView.addObject("username", "xiaoming");
        return modelAndView;
    }

    //模型和视图注入返回
    @RequestMapping("/s3")
    public ModelAndView show3(ModelAndView modelAndView) {
        modelAndView.setViewName("hello");
        modelAndView.addObject("username", "xiaogang");
        return modelAndView;
    }

    //模型返回
    @RequestMapping("/s4")
    public String show4(Model model) {
        model.addAttribute("username", "xiaohong");
        return "hello";
    }

    //request 方式返回
    @RequestMapping("/s5")
    public String show5(HttpServletRequest request) {
        request.setAttribute("username", "xiaoxu");
        return "hello";
    }

    //response返回数据
    @RequestMapping("/s6")
    public void show6(HttpServletResponse response) throws IOException {
        response.getWriter().print("Hello World");
    }

    //直接返回字符串非模板
    @RequestMapping("/s7")
    @ResponseBody
    public String show7() {
        return "xiaoming";
    }

    //直接json数据
    @RequestMapping("/s8")
    @ResponseBody
    public String show8() {
        return "{\"username\":\"zhangsan\",\"age\":18}";
    }

    //使用json包对象转json
    @RequestMapping("/s9")
    @ResponseBody
    public String show9() throws JsonProcessingException {
        User user = new User();
        user.setUsername("xiaoming");
        user.setAge(23);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        return json;
    }

    //spring容器返回对象集合
    @RequestMapping("/s10")
    @ResponseBody
    public User show10() {
        User user = new User();
        user.setUsername("xiaohong");
        user.setAge(23);
        return user;
    }
}
